package smetana.ibatis;

import com.google.inject.Provider;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * iBatis Session Management Factory Singleton.
 * @author dmitry.mamonov
 */
public class SqlSessionProvider implements Provider<SqlSession> {
    private static SqlSessionFactory instance = null;
    public static SqlSessionFactory getInstance() {
        if (instance == null) {
            String resource = "META-INF/config-ibatis-smetana.xml";
            Reader reader;
            try {
                reader = Resources.getResourceAsReader(resource);
            } catch(IOException ex){
                throw new Error(ex);
            }
            Properties props = new Properties();
            try {
                props.load(SqlSessionProvider.class.getResourceAsStream("/META-INF/db-smetana.properties"));
            } catch(IOException ex){
                throw new Error(ex);
            }
            instance = new SqlSessionFactoryBuilder().build(reader, props);
        }
        return instance;
    }

    @Override
    public SqlSession get() {
        return getInstance().openSession();
    }
}
